import Cookies from 'js-cookie';
import { getOrderPage } from '@/api/order';
import { login, getInfo, getMenus } from '@/api/system';

import { getToken, setToken, removeToken, setSiteId, getSiteId, removeSiteId, setDynamicSiteId } from '@/utils/auth';
import router, { resetRouter } from '@/router';

const user = {
    state: {
        userId: Cookies.get('userId'),
        token: getToken(),
        name: '',
        email: '',
        cname: '',
        avatar: '',
        roles: [],
        siteId: '',
        newSiteId: getSiteId() || '',
        siteList: [],
        timeZone: 0,
        routers: [],
        orderNum: 0,
        defaultPath: '/dashboard'
    },

    mutations: {
        SET_TOKEN: (state, token) => {
            state.token = token;
        },
        SET_NAME: (state, name) => {
            state.name = name;
        },
        SET_CNAME: (state, name) => {
            state.cname = name;
        },
        SET_AVATAR: (state, avatar) => {
            state.avatar = avatar;
        },
        SET_ROLES: (state, roles) => {
            state.roles = roles;
        },
        SET_USER_ID: (state, userId) => {
            state.userId = userId;
            Cookies.set('userId', userId);
        },
        SET_SITE_ID: (state, id) => {
            state.siteId = Number(id);
        },
        SET_EMAIL: (state, email) => {
            state.email = email;
        },
        SET_SITE_NEW_ID: (state, id) => {
            state.newSiteId = Number(id);
            setSiteId(Number(id));
        },
        SET_DYNAMIC_SITE_ID: (state, data) => {
            setDynamicSiteId(data.name, data.id);
        },
        SET_SITE_LIST: (state, arr) => {
            state.siteList = arr;
        },
        SET_TIME_ZONE: (state, data) => {
            state.timeZone = data.replace('UTC', '');
        },
        SET_MENUS_MAP: (state, arr) => {
            state.routers = arr;
        },
        SET_ORDER_NUM: (state, num) => {
            state.orderNum = num;
        },
        SET_DEFAULT_PATH: (state, path) => {
            state.defaultPath = path;
        }
    },

    actions: {
        // 登录
        Login ({ commit }, userInfo) {
            const { userName, password } = userInfo;
            return new Promise((resolve, reject) => {
                login({ userName: userName.trim(), password: password }).then(response => {
                    const token = response.data.token;
                    setToken(token);
                    commit('SET_TOKEN', token);
                    resolve();
                }).catch(error => {
                    reject(error);
                });
            });
        },

        // 获取用户信息
        GetInfo ({ commit, state }, data) {
            return new Promise((resolve, reject) => {
                getInfo().then(res => {
                    let { data } = res;
                    let siteList = data.siteList;
                    let userInfo = data.user;
                    commit('SET_ROLES', ['admin']);
                    commit('SET_NAME', userInfo.name);
                    commit('SET_SITE_ID', siteList.length ? siteList[0].id : []);
                    // commit('SET_DYNAMIC_SITE_ID', siteList.length ? {name: siteList[0].name, id: siteList[0].id} : {});
                    commit('SET_USER_ID', userInfo.id);
                    commit('SET_SITE_LIST', siteList);
                    commit('SET_EMAIL', userInfo.email);
                    resolve({ menus: [] });
                }).catch(e => {
                    reject(e);
                });
            });
        },
        GetMenus ({ commit, state }, id) {
            return new Promise((resolve, reject) => {
                getMenus(id).then(res => {
                    const accountName = process.env.VUE_APP_SERVER_ID === '0' ? '1281581916@qq.com' : '962244623@qq.com';
                    const data = state.email === accountName ? [...res.data, 'shop'] : res.data;
                    commit('SET_MENUS_MAP', data);
                    resolve(data);
                }).catch(e => {
                    reject(e);
                });
            });
        },

        // 登出
        LogOut ({ commit, state }) {
            return new Promise((resolve, reject) => {
                // loginout(state.token).then(() => {
                commit('SET_TOKEN', '');
                commit('SET_ROLES', []);
                removeToken();
                removeSiteId();
                resolve();
                // }).catch(error => {
                //     reject(error);
                // });
            });
        },

        // 单纯删除token
        ResetToken ({ commit }) {
            return new Promise(resolve => {
                commit('SET_TOKEN', '');
                commit('SET_ROLES', []);
                removeToken();
                removeSiteId();
                resolve();
            });
        },

        // Dynamically modify permissions
        ChangeRoles ({ commit, dispatch }, role) {
            return new Promise(async resolve => {
                const { menus } = await dispatch('GetInfo');

                resetRouter();

                // generate accessible routes map based on roles
                const accessRoutes = await dispatch('GenerateRoutes', menus, { root: true });

                // dynamically add accessible routes
                router.addRoutes(accessRoutes);

                resolve();
            });
        },
        // 获取订单数量
        GetOrderNum ({ commit, state }, siteId) {
            getOrderPage({ page: 1, pageSize: 1000, siteId }).then((res) => {
                commit('SET_ORDER_NUM', res.records.filter(s => s.status === 2).length);
            });
        },

        // 在 getUserInfo action 中修改获取用户信息后的处理逻辑
        GetUserInfo ({ commit, state, dispatch }) {
            return new Promise((resolve, reject) => {
                getInfo().then(response => {
                    // ... existing code ...

                    // 获取用户信息后，根据设备类型决定跳转路径
                    dispatch('getInfo').then(() => {
                        // 检查是否为移动设备
                        const isMobile = state.app.isMobile;

                        // 如果是移动设备，设置默认路由为订单页面
                        if (isMobile) {
                            commit('SET_DEFAULT_PATH', '/order/list');
                        }

                        resolve(response);
                    });
                }).catch(error => {
                    reject(error);
                });
            });
        }
    }
};

export default user;
